import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import '../serve/file_serve.dart';

/// 增强的PDF查看器组件，支持页面导航和位置记忆
class EnhancedPdfViewer extends StatefulWidget {
  final String filePath;
  final String? docId;
  final FileServe? fileServe;
  final String? title;

  const EnhancedPdfViewer({
    Key? key,
    required this.filePath,
    this.docId,
    this.fileServe,
    this.title,
  }) : super(key: key);

  @override
  _EnhancedPdfViewerState createState() => _EnhancedPdfViewerState();
}

class _EnhancedPdfViewerState extends State<EnhancedPdfViewer> {
  PDFViewController? _pdfController;
  final TextEditingController _pageController = TextEditingController();
  
  int _currentPage = 0;
  int _totalPages = 0;
  bool _isLoading = true;
  bool _hasError = false;
  String? _errorMessage;
  bool _isPageControllerVisible = false;
  bool _isInitializing = true; // 标记是否在初始化阶段
  bool _isJumping = false; // 标记是否正在跳转页面，用于保护用户误触
  int? _targetPage; // 记录要跳转的目标页面

  @override
  void initState() {
    super.initState();
    _loadLastReadingPosition();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _saveCurrentPosition();
    super.dispose();
  }

  /// 加载上次阅读位置
  Future<void> _loadLastReadingPosition() async {
    if (widget.docId != null && widget.fileServe != null) {
      try {
        final position = await widget.fileServe!.getDocumentReadingPosition(widget.docId!);
        if (position != null) {
          final lastPage = position['current_page'] ?? 0;
          print('PDF查看器: 加载上次阅读位置 - 第 $lastPage 页');
          setState(() {
            _targetPage = lastPage; // 记录目标页面
          });
        }
      } catch (e) {
        print('PDF查看器: 加载阅读位置失败: $e');
      }
    }
  }

  /// 保存当前阅读位置
  Future<void> _saveCurrentPosition() async {
    if (widget.docId != null && widget.fileServe != null && _totalPages > 0) {
      try {
        await widget.fileServe!.saveDocumentReadingPosition(
          widget.docId!,
          _currentPage,
          _totalPages,
        );
      } catch (e) {
        print('PDF查看器: 保存阅读位置失败: $e');
      }
    }
  }

  /// 精确页面跳转，确保页面正确对齐（用户主动操作，不需要保护）
  Future<void> _preciseGoToPage(int page) async {
    if (_pdfController == null || page < 0 || page >= _totalPages) return;
    
    try {
      print('PDF查看器: 开始精确跳转到第 ${page + 1} 页');
      
      // 首次跳转
      await _pdfController!.setPage(page);
      
      // 等待页面渲染稳定
      await Future.delayed(Duration(milliseconds: 400));
      
      // 二次确认跳转，确保页面完全对齐
      await _pdfController!.setPage(page);
      
      print('PDF查看器: 精确跳转到第 ${page + 1} 页完成');
    } catch (e) {
      print('PDF查看器: 精确跳转失败: $e');
    }
  }

  /// 历史位置恢复跳转，带有保护机制防止用户误触
  Future<void> _restoreHistoryPosition(int page) async {
    if (_pdfController == null || page < 0 || page >= _totalPages) return;
    
    // 设置跳转保护，防止用户误触
    setState(() {
      _isJumping = true;
    });
    
    try {
      print('PDF查看器: 开始受保护的历史位置恢复到第 ${page + 1} 页');
      
      // 首次跳转
      await _pdfController!.setPage(page);
      
      // 等待页面渲染稳定
      await Future.delayed(Duration(milliseconds: 400));
      
      // 二次确认跳转，确保页面完全对齐
      await _pdfController!.setPage(page);
      
      // 更新当前页面状态
      setState(() {
        _currentPage = page;
      });
      
      print('PDF查看器: 历史位置恢复到第 ${page + 1} 页完成');
    } catch (e) {
      print('PDF查看器: 历史位置恢复失败: $e');
    } finally {
      // 跳转完成后，延迟解除保护，确保位置稳定
      await Future.delayed(Duration(milliseconds: 1000));
      if (mounted) {
        setState(() {
          _isJumping = false;
        });
        print('PDF查看器: 历史位置恢复保护已解除');
      }
    }
  }

  /// 跳转到指定页面（用户主动操作，不需要保护）
  Future<void> _goToPage(int page) async {
    print('PDF查看器: 尝试跳转到第 ${page + 1} 页，当前总页数: $_totalPages，控制器状态: ${_pdfController != null}');
    
    if (_pdfController != null && page >= 0 && page < _totalPages) {
      try {
        print('PDF查看器: 开始执行页面跳转...');
        await _pdfController!.setPage(page);
        
        // 跳转后稍作延迟，然后重新设置页面位置确保对齐
        await Future.delayed(Duration(milliseconds: 300));
        
        // 重新设置一次页面确保正确对齐
        try {
          await _pdfController!.setPage(page);
          print('PDF查看器: 页面重新对齐完成');
        } catch (e) {
          print('PDF查看器: 页面重新对齐失败: $e');
        }
        
        final currentPage = await _pdfController!.getCurrentPage();
        print('PDF查看器: 请求跳转到索引 $page，最终页面索引: $currentPage');
        
        setState(() {
          _currentPage = page;
        });
        // 立即保存新的页面位置
        await _saveCurrentPosition();
        print('PDF查看器: 成功跳转到第 ${page + 1} 页并保存位置');
      } catch (e) {
        print('PDF查看器: 跳转页面失败: $e');
        _showErrorSnackBar('跳转到第 ${page + 1} 页失败');
      }
    } else {
      print('PDF查看器: 跳转条件不满足 - 控制器: ${_pdfController != null}, 页面范围: $page >= 0 && $page < $_totalPages');
    }
  }

  /// 上一页
  Future<void> _previousPage() async {
    if (_currentPage > 0) {
      await _goToPage(_currentPage - 1);
    }
  }

  /// 下一页
  Future<void> _nextPage() async {
    if (_currentPage < _totalPages - 1) {
      await _goToPage(_currentPage + 1);
    }
  }

  /// 显示页面跳转对话框
  void _showPageJumpDialog() {
    _pageController.text = (_currentPage + 1).toString();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('跳转到页面'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('总共 $_totalPages 页，当前第 ${_currentPage + 1} 页'),
            SizedBox(height: 16),
            TextField(
              controller: _pageController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: '页码',
                hintText: '输入页码 (1-$_totalPages)',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final page = int.tryParse(_pageController.text);
              if (page != null && page >= 1 && page <= _totalPages) {
                Navigator.of(context).pop();
                print('PDF查看器: 用户输入跳转到第 $page 页，转换为索引 ${page - 1}');
                
                // 使用精确跳转方法
                final targetIndex = page - 1;
                _preciseGoToPage(targetIndex).then((_) {
                  setState(() {
                    _currentPage = targetIndex;
                  });
                  _saveCurrentPosition();
                });
              } else {
                _showErrorSnackBar('请输入有效的页码 (1-$_totalPages)');
              }
            },
            child: Text('跳转'),
          ),
        ],
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // PDF查看器主体
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 20,
                  offset: Offset(0, 10),
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(20),
              child: _hasError
                  ? _buildErrorView()
                  : Stack(
                      children: [
                        IgnorePointer(
                          ignoring: _isJumping, // 在跳转期间忽略所有触控事件
                          child: PDFView(
                            filePath: widget.filePath,
                            enableSwipe: true,
                            swipeHorizontal: true,
                            autoSpacing: true,
                            pageFling: true,
                            pageSnap: true,
                            defaultPage: 0, // 总是从第0页开始，然后通过代码跳转
                            fitPolicy: FitPolicy.WIDTH, // 改为宽度适配，避免水平偏移
                            preventLinkNavigation: false,
                          onRender: (pages) {
                            setState(() {
                              _totalPages = pages ?? 0;
                              _isLoading = false;
                            });
                            print('PDF查看器: 渲染完成，总页数: $_totalPages');
                            
                            // PDF渲染完成后，跳转到上次阅读位置
                            if (_isInitializing && _targetPage != null && _targetPage! > 0) {
                              print('PDF查看器: 准备恢复历史位置 - 第 ${_targetPage! + 1} 页');
                              
                              Future.delayed(Duration(milliseconds: 800), () {
                                if (_pdfController != null) {
                                  // 使用带保护的历史位置恢复方法
                                  _restoreHistoryPosition(_targetPage!);
                                  _targetPage = null; // 清除目标页面
                                }
                                _isInitializing = false;
                              });
                            } else {
                              _isInitializing = false;
                            }
                          },
                          onError: (error) {
                            setState(() {
                              _hasError = true;
                              _errorMessage = error.toString();
                              _isLoading = false;
                            });
                            print('PDF查看器: 加载错误: $error');
                          },
                          onPageError: (page, error) {
                                                         _showErrorSnackBar('第 ${(page ?? 0) + 1} 页加载失败');
                            print('PDF查看器: 页面错误: $error');
                          },
                          onViewCreated: (PDFViewController pdfViewController) {
                            _pdfController = pdfViewController;
                            print('PDF查看器: PDF控制器已创建');
                          },
                          onPageChanged: (page, total) {
                            print('PDF查看器: onPageChanged回调 - 页面索引: $page, 总页数: $total, 保护状态: $_isJumping');
                            
                            // 在跳转保护期间，忽略页面变化事件，防止误触重置位置
                            if (_isJumping) {
                              print('PDF查看器: 跳转保护中，忽略页面变化事件');
                              return;
                            }
                            
                            setState(() {
                              _currentPage = page ?? 0;
                              _totalPages = total ?? 0;
                            });
                            
                            // 只有在非初始化阶段才保存位置，避免覆盖恢复的位置
                            if (!_isInitializing) {
                              _saveCurrentPosition();
                              print('PDF查看器: 页面变化到第 ${_currentPage + 1} 页，已保存位置');
                            }
                          },
                          ),
                        ),
                        
                        // 加载指示器
                        if (_isLoading)
                          Container(
                            color: Colors.white,
                            child: Center(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  CircularProgressIndicator(
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      Color(0xFF667eea),
                                    ),
                                  ),
                                  SizedBox(height: 16),
                                  Text(
                                    '正在加载PDF文档...',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        
                        // 跳转保护指示器
                        if (_isJumping)
                          Container(
                            color: Colors.black.withOpacity(0.3),
                            child: Center(
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(16),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.2),
                                      blurRadius: 8,
                                      offset: Offset(0, 4),
                                    ),
                                  ],
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    SizedBox(
                                      width: 20,
                                      height: 20,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor: AlwaysStoppedAnimation<Color>(
                                          Color(0xFF667eea),
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 12),
                                    Text(
                                      '正在跳转到历史位置...',
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.w500,
                                        color: Colors.grey[700],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
            ),
          ),
        ),
        
        SizedBox(height: 16),
        
        // 页面导航控制栏
        _buildNavigationBar(),
      ],
    );
  }

  Widget _buildErrorView() {
    return Container(
      padding: EdgeInsets.all(32),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.red[50],
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.red[200]!),
              ),
              child: Icon(
                Icons.error_outline,
                size: 48,
                color: Colors.red[400],
              ),
            ),
            SizedBox(height: 16),
            Text(
              'PDF加载失败',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Colors.grey[700],
              ),
            ),
            SizedBox(height: 8),
            Text(
              _errorMessage ?? '未知错误',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16,
            offset: Offset(0, 8),
          ),
        ],
      ),
      child: Row(
        children: [
          // 上一页按钮
          _buildNavButton(
            icon: Icons.chevron_left,
            tooltip: '上一页',
            onPressed: _currentPage > 0 ? _previousPage : null,
          ),
          
          SizedBox(width: 12),
          
          // 页面信息
          Expanded(
            child: GestureDetector(
              onTap: _totalPages > 0 ? _showPageJumpDialog : null,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '第 ${_currentPage + 1} 页',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Colors.grey[700],
                      ),
                    ),
                    if (_totalPages > 0) ...[
                      Text(
                        ' / $_totalPages',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[500],
                        ),
                      ),
                      SizedBox(width: 8),
                      Icon(
                        Icons.touch_app,
                        size: 16,
                        color: Colors.grey[500],
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ),
          
          SizedBox(width: 12),
          
          // 下一页按钮
          _buildNavButton(
            icon: Icons.chevron_right,
            tooltip: '下一页',
            onPressed: _currentPage < _totalPages - 1 ? _nextPage : null,
          ),
        ],
      ),
    );
  }

  Widget _buildNavButton({
    required IconData icon,
    required String tooltip,
    VoidCallback? onPressed,
  }) {
    final isEnabled = onPressed != null;
    
    return Tooltip(
      message: tooltip,
      child: Container(
        width: 44,
        height: 44,
        decoration: BoxDecoration(
          gradient: isEnabled
              ? LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                )
              : null,
          color: isEnabled ? null : Colors.grey[200],
          borderRadius: BorderRadius.circular(12),
          boxShadow: isEnabled
              ? [
                  BoxShadow(
                    color: Color(0xFF667eea).withOpacity(0.3),
                    blurRadius: 8,
                    offset: Offset(0, 4),
                  ),
                ]
              : null,
        ),
        child: Material(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(12),
          child: InkWell(
            borderRadius: BorderRadius.circular(12),
            onTap: onPressed,
            child: Center(
              child: Icon(
                icon,
                color: isEnabled ? Colors.white : Colors.grey[400],
                size: 20,
              ),
            ),
          ),
        ),
      ),
    );
  }
} 